<?php
/*
 * 集成阿里云通信轻量级短信接口
 *
 * 2018/07/13
 */

namespace app\common\model;

use think\Exception;
use think\Model;

class Jhsms extends Model
{


    private $corpid = 'NJJT000707';
    private $pwds = 'hy2010@';

    /**
     *Author:xuanfeng
     *Date:2020-01-14 18:20:54
     *For: 短信接口查询调用
     */
    public function mysms($s)
    {
        $uid = $this->corpid;
        $passwd = $this->pwds;
        if ($s == 1) {
            $request_url = "https://sdk3.028lk.com:9988/SelSum.aspx?CorpID=" . $uid . "&Pwd=" . $passwd;
        }
        if ($s == 2) {
            $request_url = "https://sdk3.028lk.com:9988/LinkWS.asmx/NotSend?CorpID=" . $uid . "&Pwd=" . $passwd;
        }
        $result = file_get_contents($request_url);
        if ($result > 0) {
            if ($s == 1) {
                echo '当前套餐可用量剩余:' . $result . '条<br />';
                echo "请求时间" . date("Y-m-d H:i:s");
            }
        } else {
            if ($s == 2) {
                echo "请求时间" . date("Y-m-d H:i:s") . '<br />';
                echo '当前由于发送太过频繁、黑名单、非法操作等被封的号码（为空表示没有）:' . $result . '<br />';
                exit;
            }
            echo "请求失败, 错误提示代码: " . $result;
        }
        exit;
    }





    //1验证码  2短信通知

    /**
     *Author:xuanfeng
     *Date:2020-01-14 18:20:54
     *For: 短信接口查询调用
     */
    function set_phone($tel, $message = 1, $code = '')
    {
        header("Content-type: text/html; charset=utf-8");
        date_default_timezone_set('PRC');
        $uid = $this->corpid;
        $passwd = $this->pwds;
        $types = $message;

        //检查短信开关 xuanfeng 2020-02-27
        if (config("setting.smsmy_on") == 2) {
            $ary = ['status' => '10000', 'tips' => '短信通道已关闭，请联系管理员！'];
        }

        if ($message == 1) {
            if (empty($code)) {
                $code = rand(1000, 9999);
            }
            $message = "您好，您的短信验证码为" . $code . "，如非本人操作,请忽略。【全民共享】";
        } else if ($message == 2) {
            $message = "尊敬的用户您好，您有新的订单请尽快查看。【全民共享】";
        } else {
            $ary = ['status' => '10000', 'tips' => '系统错误，请稍后再试！'];
            return $ary;
            exit;
        }

        $msg = rawurlencode(mb_convert_encoding($message, "gb2312", "utf-8"));
        $request_url = "https://sdk3.028lk.com:9988/BatchSend2.aspx?CorpID=" . $uid . "&Pwd=" . $passwd . "&Mobile=" . $tel;
        $gateway = $request_url . "&Content=" . $msg . "&Cell=&SendTime=";
        $result = file_get_contents($gateway);
        if ($result > 0) {
            $ary = ['status' => '10001', 'tips' => 'success', 'recode' => $result, 'code' => $code];
        } else {
            $ary = ['status' => '10000', 'tips' => '发送失败，错误代码：' . $result];
        }
        return $ary;
    }

    //设置信息
    private $settings = [];

    public function __construct()
    {
        $this->settings = config('jhsms');
    }

    /**
     * @param string $mobile 手机号
     * @param int $type 验证码类型 1 注册验证码 2 找回密码 3 用户登录
     **/
    public function send_sms($mobile, $type)
    {
        if ($type == 2 || $type == 3) {
            if (!User::exists($mobile)) {
                throw new Exception("你还未注册，请先注册");
            }
        }
        if ($type == 1) {
            if (User::exists($mobile)) {
                throw new Exception("你已注册，可以直接登录");
            }
        }
        //检查短信开关 xuanfeng 2020-02-27
        if (config("setting.smsmy_on") == 2) {
            throw new Exception('短信通道已关闭，请联系管理员！');
        }
        //生成验证码
        $captcha = self::generateCaptcha($mobile, $type);
        //记录验证码记录
        $insertId = db("sms_log")->insertGetId([
            "telephone" => $mobile,
            "vcode" => $captcha,
            "exp_time" => time() + 240,
            "type" => $type,
            "create_time" => time()
        ]);
        if (!$insertId) {
            throw new Exception("验证码发送异常");
        }
        //老的短信接口注释，使用新的短信接口
        $ary = $this->set_phone($mobile, 1, $captcha);

        if ($ary['status'] == '10001') {
            //存储短信验证码
            db("sms_log")->where("id", $insertId)->update(['status' => 1]);
        } else {
            //返回内容异常，以下可根据业务逻辑自行修改
            db("sms_log")->where("id", $insertId)->update(["status" => -1, "remarks" => "系统异常" . $ary['tips']]);
            throw new DeveloperException($ary['tips']);
        }
    }


    /**
     * 发送订单提醒
     */
    public function send_order_tips($mobile)
    {
        if (!User::exists($mobile)) {
            return false;
//            throw new Exception("你还未注册，注册后登录");
        }
        //记录短信记录
        $insertId = db("sms_log")->insertGetId([
            "telephone" => $mobile,
            "vcode" => "0000",
            "exp_time" => time() + 1000,
            "type" => 4,
            "create_time" => time()
        ]);
        if (!$insertId) {
            return false;
        }
        //尊敬的用户您好，您有新的订单请尽快查看，换短信接口
        $ary = model('Jhsms')->set_phone($mobile, 2);
        if ($ary['status'] == '10001') {
            db("sms_log")->where("id", $insertId)->update(['status' => 1]);
            return true;
        } else {
            db("sms_log")->where("id", $insertId)->update(["status" => -1, "remarks" => "系统异常" . $ary['tips']]);
//          throw new DeveloperException('请求发送短信失败');
            return false;
        }

    }

    /**
     * 获取验证码
     * @param $mobile
     * @param $type
     * @return string
     * @throws UserException
     */
    static public function generateCaptcha($mobile, $type)
    {
        $code_res = self::getVcode($mobile, $type);
        if (!$code_res) {
            //生成验证码
            return random(6, true);
        }
        if ($code_res["exp_time"] < time()) {
            //验证码已过期标记已过期
            db("sms_log")->where("id", $code_res["id"])->update(["status" => 3]);
            return random(6, true);
        } else {
            throw new UserException("验证码已发送,请查看手机短信!");
        }
    }

    /**
     * 获取验证码记录
     * @param $mobile
     * @param $type
     */
    public static function getVcode($mobile, $type)
    {
        $res = db("sms_log")->where("telephone", $mobile)->where("type", $type)->where("status", 1)->find();
        return $res;
    }

    public static function verifyCaptcha($mobile, $captcha, $type)
    {
        $res = db("sms_log")->where("telephone", $mobile)->where("type", $type)->where("vcode", $captcha)->find();
        if (empty($res)) {
            throw new Exception("验证码错误");
        }
        //if ($res["status"] != 1 || $res["exp_time"] < time()) {
        //echo $res["exp_time"];exit;
        if ($res["status"] != 1 || $res["exp_time"] < time()) {
            throw new Exception("验证码已过期");
        }
        db("sms_log")->where("id", $res["id"])->update(["status" => 2]);
    }

    /**
     * 请求接口返回内容
     * @param string $url [请求的URL地址]
     * @param string $params [请求的参数]
     * @param int $ipost [是否采用POST形式]
     * @return  string
     */
    private function juhecurl($url, $params = false, $ispost = 0)
    {
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($params) {
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }
        $response = curl_exec($ch);
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }

}
